(function(){

$(function(){

    var pageCount=[];
    var AudioUrl=[]; //所有 音频 资源
    var All_audio=[];  //定义空 音频元素数组 对象
    var timer=null;
    var timer1=null;
    //头部点击显示更多 效果
    $('.icon').on('tap', function () {
        //console.log('I am icon');
        if($(this).hasClass('icon_more')){
            console.log('111');
            $('.intro').css('height','46px');
            $(this).removeClass('icon_more').addClass('icon');
        }else{
            $('.intro').css('height','auto');
            $(this).removeClass('icon').addClass('icon_more');
        }
    });


    //nav tab标签切换 效果
    $('.nav').on('tap','li', function () {
    var index=$(this).attr('class');
        $('.c2').hide();
        $('#'+index).show();

        //点击的是标签二  发送ajax请求
        if($(this).hasClass('a2')){
            //console.log('I am a2');
            // 发起请求
            //$.ajax({
            //    type:'get',
            //    url:'',
            //    success: function (data) {
            //        console.log(data.data);
            //    },
            //    error: function () {
            //        alert('获取数据失败!');
            //    }
            //
            //})
        }
    });


    for(var j=0;j<$('i').length;j++){
       //console.log($('i').eq(i))
       // $('i')[j].setAttribute('class',j);
    }


    //发送ajax请求 请求数据
    var num=1;
    //请求所有音频数据
    $.ajax({
        type:'get',
        url:'http://api.heardtech.com/Get/Music?page='+num+"&token_key=c4ca4238a0b923820dcc509a6f75849b",
        dataType:"json",
        success: function (data) {
            //console.log('接受数据成功');
            //console.log(data);
            //    pageCount.push(data.data.data);
            pageCount=data.data.data;

                 //console.log(data.data.data);
                 //console.log(pageCount.length);

            var html=``;
           // console.log(result);
            for(var i=0;i<pageCount.length;i++){
                var obj=pageCount[i];
                AudioUrl.push(obj.voiceurl);
                html+=`
                     <li>
                        <img src="img/playing.gif" class="playImg h1" >
                        <img src="img/paused_Img_02.png" class="pauseImg h1" />
                        <span>VL.${obj.number}:&nbsp;&nbsp;</span>${obj.title}
                        <i class="p${i}" data-src="${obj.voiceurl}" id="${obj.number}"></i>
                        <audio id="${i}" preload="none"></audio>
                        <!--进度条样式-->
                        <div id="progressWrap${obj.number}" class="progressWrap">
                            <div id="playProgress${obj.number}">
                            </div>
                        </div>
                    </li>
                `;
            }
            $('.ul_list').append(html);
            $('#Page_sum').html(`(${data.data.page_sum})`);

           // console.log(AudioUrl);
            //console.log(AudioUrl);

        },
        error: function () {
            alert('请求失败！')
        }
    });

    //点击 加载更能多 获得5条数据
    $(".pullUpLabel").on('tap', function () {
            num=pageCount.length+1;
            console.log(num);
        $('.orderPlay-btn').html('顺序播放');
        $.ajax({
            type:'get',
            url:'http://api.heardtech.com/Get/Music?page='+num+"&token_key=c4ca4238a0b923820dcc509a6f75849b",
            dataType:"json",
            success: function (data) {
                //console.log('接受数据成功');
                //console.log(data);
               var result=data.data.data;
                pageCount=pageCount.concat(result);
                AudioUrl=[];
                //pageCount.push(data.data.data);
               // console.log(result);
                //pageCount=[];
                if(result.length<5){
                    $('.pullUpLabel').html('没有更更多数据可以加载啦！');
                }
                var html=``;
                // console.log(result);
                for( var i=0;i<result.length;i++){//此处为 全局i
                        var obj=result[i];
                   // console.log(obj);
                   AudioUrl.push(obj.voiceurl);
                    html+=`
                     <li >
                        <img src="img/playing.gif" class="playImg h1" >
                        <img src="img/paused_Img_02.png" class="pauseImg h1" />
                        <span>VOL.${obj.number}:&nbsp;&nbsp;</span>${obj.title}
                        <i id="${obj.number}" class="p${i}" data-src="${obj.voiceurl}"></i>
                        <audio id="${i}" preload="none"></audio>
                        <!--进度条样式-->
                        <div id="progressWrap${obj.number}" class="progressWrap">
                            <div id="playProgress${obj.number}">
                            </div>
                        </div>
                    </li>
                `;
                }
                $('.ul_list').append(html);
            },
            error: function () {
                alert('请求失败！')
            }
        });
    });
    //返回其所有兄弟元素 函数
    function siblings(el){
        var Asiblings=[];
        var Audio=document.getElementsByTagName('audio');
        for(var i= 0,len=Audio.length;i<len;i++){
            if(Audio[i]!=el){
                Asiblings.push(Audio[i]);
            }
        }
        return Asiblings;
    }
    //console.log($('i'));
    //重载所有的兄弟音频

    $('.ul_list').on('tap','i',function(){
        console.log($(this).attr('id'));//当前元素id
        var Iid=$(this).attr('id');
        //console.log(All_audio);
        //if(timer!=null){
        //     clearInterval(timer);
        //     timer=null;
        //}else if(timer1!=null){
        //    clearInterval(timer);
        //    timer=null;
        //}
        //function GetQueryString(name){
        //    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        //    var r = window.location.search.substr(1).match(reg);
        //    if(r!=null)return  unescape(r[2]); return null;
        //}
        //alert(GetQueryString('token_key'));
        //var showProgress = document.getElementById(`showProgress${index}`);
        // console.log($('i'));
        // console.log(c);
        //console.log($("i").index($('.'+c)));  //返回 当前元素 在当前集合中的下标
        //console.log($('audio').eq(index));
        //console.log(that);
        //"&token_key="+GetQueryString('token_key')
        var c=$(this).attr('class');
        var index=$('i').index($('.'+c));
       // console.log($('i'));
        var that=$('audio').eq(index)[0]; //当前音频元素 必须为原生对象
        

       // console.log(index);

        //audio播放进度条
        function getProgress(){
            var percent = that.currentTime / that.duration;
            //最外层css样式
            $(progressWrap).addClass('progressWrap');
            //最内层css样式
            $(playProgress).addClass('playProgress');
            playProgress.style.width = percent * (progressWrap.offsetWidth) - 2 + "px";
            //showProgress.innerHTML = (percent * 100).toFixed(1) + "%";
        }
        //<i id="${obj.number}" class="p${i}" data-src="${obj.voiceurl}"></i>
        //    <audio id="${i}" preload="none"></audio>
        //        <!--进度条样式-->
        //    <div id="progressWrap${obj.number}" class="progressWrap">
        //    <div id="playProgress${obj.number}">
        //    </div>
        //    </div>
        for(var z=0;z<siblings(that).length;z++){
            siblings(that)[z].load();
            siblings(that)[z].pause();
          $(siblings(that)[z]).next().children().css('width',0); //重载所有的 兄弟进度条
             //siblings(that)[z].currentTime=0;
            // siblings(that)[z].pause();
        }
        

        
        var currentTime=Date.now();
            if(that.paused || that.ended||that.src===''){
               // if(that.src===""){//实现点击添加 src
                    that.src=$(this).data('src');
                //}//else if(timer!=null){
                //    clearInterval(timer);
                //    timer=null;
                //}
                var progressWrap = document.getElementById(`progressWrap${Iid}`);
                console.log("最外层元素为",progressWrap);
                var playProgress = document.getElementById(`playProgress${Iid}`);
                console.log('最内层元素为',playProgress);
                if (that.ended ){
                    that.currentTime = 0;
                }
                $('i').css('background','');
                that.play();
                $('.ul_list').find('img').hide();
                $(this).siblings('img.playImg').show();
                $(this).css('background','url(img/sprite2.png) -60px -280px no-repeat');
                progressFlag = setInterval(getProgress, 60);
            }else{
                that.removeEventListener('ended',Order,false);//解除事件绑定
                $('.orderPlay-btn').html('开启顺序播放');
                that.pause();
                //if(timer1!=null){clearInterval(timer);timer=null;}
                $('.ul_list').find('img').hide();
                //$('img.h1').addClass('playImg');
                $(this).siblings('img.pauseImg').show();
                $(this).css('background','url("img/sprite2.png") 0 -280px no-repeat');
                //clearInterval(progressFlag);
                //清除监听
                //clearInterval(timer);
                //timer=null;
           }
        
           //监听结束 事件
            that.addEventListener("ended", function() {
                //默认情况下 this-->音频对象
                $('.ul_list').find('img').hide();
                //console.log($(this));
                $(this).css('background','url("img/sprite2.png") 0 -280px no-repeat');
                //clearInterval(progressFlag);

            }.bind(this), false);
        var lastRunTime=Date.now();
        var   protectTime=500;//设置保护性延时 单位毫秒，不要小于50 建议100以上
        if((currentTime-lastRunTime)<protectTime){
            return;//两次执行太过频繁，直接退出
        }
            
    });

    //点击按钮循环播放
    $('.orderPlay-btn').on('tap', function () {

        $('.ul_list').find('img').hide();
        for(let i=0;i<All_audio.length;i++){
            All_audio[i].load();
        }
        All_audio=document.getElementsByTagName('audio');
       // console.log(All_audio);
         var firstAudio=All_audio[0];
         var firstId=$(firstAudio).prev().attr('id');
         var progressWrap=document.getElementById(`progressWrap${firstId}`);
         var playProgress = document.getElementById(`playProgress${firstId}`);

        for(var z=0;z<siblings(firstAudio).length;z++){
            $(siblings(firstAudio)[z]).next().children().css('width',0); //重载所有的 兄弟进度条
        }

        // timer=setInterval(function () {
            if(firstAudio.src===''||firstAudio.src!=""){
                firstAudio.src=$(firstAudio).prev().data('src');
                firstAudio.play();
                $('.ul_list').find('i').css('background','url(img/sprite2.png) 0 -280px no-repeat');
                // console.log("我是图片元素",that.siblings('img.playImg'));
                $(firstAudio).siblings('img.playImg').show();
                $(firstAudio).prev().css('background','url(img/sprite2.png) -60px -280px no-repeat');
                progressFlag = setInterval(getProgress1, 60);
            }
     // },500);
            $(this).html('开启顺序播放');
            //console.log(All_audio.length);
            for(var d=0,len=All_audio.length;d<len-1;d++){
                All_audio[d].addEventListener('ended', Order,false);

            $(this).html('顺序播放中');
        }

        //audio播放进度条
        function getProgress1(){
            var percent = firstAudio.currentTime / firstAudio.duration;
            //最外层css样式
            $(progressWrap).addClass('progressWrap');
            //最内层css样式
            $(playProgress).addClass('playProgress');
            playProgress.style.width = percent * (progressWrap.offsetWidth) - 2 + "px";
            //showProgress.innerHTML = (percent * 100).toFixed(1) + "%";
        }

    });



    //监听 函数内容
   function Order(){
       this.pause();
       // console.log($(All_audio).index($(this)));  //获得当前播放元素的下标  *********************************************************************
       //console.log('我播放完啦！',this);
       var  that=$(this).parent().next().find('audio');
       var Tid=that.prev().attr('id');
       var progressWrap=document.getElementById(`progressWrap${Tid}`);
       var playProgress = document.getElementById(`playProgress${Tid}`);
       //console.log(Tid);
      // console.log(playProgress);
       //console.log('下一个播放元素的小标为'+$(All_audio).index(that));
       // console.log(that[0]);
       //console.log(that);
       if(that[0].src===""){
           that[0].src=that.prev().data('src');
           that[0].play();
           $('.ul_list').find('img').hide();
           $('.ul_list').find('i').css('background','url(img/sprite2.png) 0 -280px no-repeat');
           //console.log("我是图片元素",that.siblings('img.playImg'));
           that.siblings('img.playImg').show();
           that.prev().css('background','url(img/sprite2.png) -60px -280px no-repeat');
           progressFlag = setInterval(getProgress, 60);
           //progressFlag = setInterval(getProgress, 60);0
           //console.log("我是that[0]",that[0]);
           //console.log(All_audio[All_audio.length-1]);
           if(that[0]==All_audio[All_audio.length-1]){//如果是 数组中 最后一个元素
               that[0].play();
               progressFlag = setInterval(getProgress, 60);
              // console.log("我是最后一个元素啦");
               that[0].addEventListener('ended',function(){
                  // console.log('我放完啦！');
                   $('.ul_list').find('img').hide();
                   //$('.ul_list').find('i').css('background','url(img/sprite2.png) 0 -280px no-repeat');
                   //that.siblings('img.pauseImg').show();
                   that.prev().css('background','url(img/sprite2.png) 0 -280px no-repeat');
                   $(".orderPlay-btn").html('开启顺序播放');
                   //clearInterval(timer);
                   //timer=null;
               },false);
           }
       }else if(that[0].src!=""){//已经加载过 一次 之后
           $('.ul_list').find('img').hide();
           that[0].play();
           $('.ul_list').find('i').css('background','url(img/sprite2.png) 0 -280px no-repeat');
           // console.log("我是图片元素",that.siblings('img.playImg'));
           that.siblings('img.playImg').show();
           that.prev().css('background','url(img/sprite2.png) -60px -280px no-repeat');
       }

       //audio播放进度条
       function getProgress(){
           var percent = that[0].currentTime / that[0].duration;
           //最外层css样式
           $(progressWrap).addClass('progressWrap');
           //最内层css样式
           $(playProgress).addClass('playProgress');
           playProgress.style.width = percent * (progressWrap.offsetWidth) - 2 + "px";
           //showProgress.innerHTML = (percent * 100).toFixed(1) + "%";
       }
   }
});
})();
